package com.ywx.yypicturebackend.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ywx.yypicturebackend.annotation.AuthCheck;
import com.ywx.yypicturebackend.api.aliyunai.AliyunAiService;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ywx.yypicturebackend.api.aliyunai.model.GetOutPaintingTaskResponseResult;
import com.ywx.yypicturebackend.api.imagesearch.ImageSearchApiFacade;
import com.ywx.yypicturebackend.api.imagesearch.model.ImageSearchResult;
import com.ywx.yypicturebackend.common.BaseResponse;
import com.ywx.yypicturebackend.common.DeleteRequest;
import com.ywx.yypicturebackend.common.ResultUtils;
import com.ywx.yypicturebackend.constant.UserConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.model.dto.picture.*;
import com.ywx.yypicturebackend.model.entity.Picture;
import com.ywx.yypicturebackend.model.entity.Space;
import com.ywx.yypicturebackend.model.entity.User;
import com.ywx.yypicturebackend.model.enums.PictureReviewStatusEnum;
import com.ywx.yypicturebackend.model.vo.PictureTagCategory;
import com.ywx.yypicturebackend.model.vo.PictureVO;
import com.ywx.yypicturebackend.service.PictureService;
import com.ywx.yypicturebackend.service.SpaceService;
import com.ywx.yypicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/picture")
public class PictureController {


    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliyunAiService aliyunAiService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //构造本地缓存
    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();


    /**
     * 图片上传(上传新图片或修改旧图片)
     *
     * @param multipartFile        前端传来的文件
     * @param pictureUploadRequest
     * @param request
     * @return PictureVO
     */
    @PostMapping("/upload")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> pictureUpload(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        pictureVO.setUser(userService.getUserVo(loginUser));
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量上传图片,仅管理员可用
     *
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> pictureUploadByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                      HttpServletRequest request) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Integer uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);

        return ResultUtils.success(uploadCount);

    }

    /**
     * 通过Url上传图片
     *
     * @param pictureUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> pictureUploadByUrl(@RequestBody PictureUploadRequest pictureUploadRequest,
                                                      HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(pictureUploadRequest.getFileUrl(), pictureUploadRequest, loginUser);
        pictureVO.setUser(userService.getUserVo(loginUser));
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long pictureId = deleteRequest.getId();
        //删除图片
        pictureService.deletePicture(loginUser, pictureId);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片数据,仅管理员可以,一些简单的逻辑可以不用封装到Service层直接写在Controller层
     *
     * @param updateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest updateRequest,
                                               HttpServletRequest request) {

        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //DTO =》 实体类
        Picture picture = new Picture();
        BeanUtils.copyProperties(updateRequest, picture);

        //将list转换成string
        picture.setTags(JSONUtil.toJsonStr(updateRequest.getTags()));

        //判断是否存在
        long id = updateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR);

        //填充审核字段
        User loginUser = userService.getLoginUser(request);
        pictureService.fileReviewParams(picture, loginUser);


        //更新数据
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);


        return ResultUtils.success(true);
    }


    /**
     * 根据id获取图片的所有信息,仅管理员可用
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);

        Picture picture = pictureService.getById(id);

        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        return ResultUtils.success(picture);
    }

    /**
     * 根据id获取图片封装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);


        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);

        User loginUser = userService.getLoginUser(request);

        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            //权限校验
            pictureService.checkPictureAuth(picture, loginUser);
        }


        return ResultUtils.success(pictureService.getPictureVO(picture, request));
    }

    /**
     * 获取图片分页列表,仅管理员可用
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long pageSize = pictureQueryRequest.getPageSize();


        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));

        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);


        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null) {
            //查询公共图库的图片

            //普通用户只能查审核通过的图片
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            //校验私有空间权限
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            User loginUser = userService.getLoginUser(request);
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权限操作该空间");

        }


        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 返回封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }


    /**
     * 分页获取图片列表（封装类）通过Redis缓存
     */
    /*  现阶段使用本地缓存足矣
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {

        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //普通用户只能查审核通过的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());



        //构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = "yypicture:listPictureVOByPage:" + hashKey;

//        查询缓存
        ValueOperations<String,String> opsForValue = stringRedisTemplate.opsForValue();
        String cachedValue = opsForValue.get(redisKey);

        //缓存命中
        if (cachedValue!=null){
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);

            return ResultUtils.success(cachedPage);
        }

        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        //获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);


        //将数据库中的结果放入缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        long timeout = 300 + RandomUtil.randomLong(0,300);//设置较为随机的过期时间,防止缓存雪崩
        opsForValue.set(redisKey,cacheValue,timeout, TimeUnit.SECONDS);

        // 返回封装类
        return ResultUtils.success(pictureVOPage);
    }

*/

    /**
     * 分页获取图片列表（封装类）通过Redis和本地缓存构建多级缓存
     */
    @Deprecated//当开发者使用被 @Deprecated 标记的代码时，编译器会生成警告（例如 [deprecation]），提醒该元素存在风险或已过时
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request) {

        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //普通用户只能查审核通过的图片
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());


        //构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String cacheKey = "yypicture:listPictureVOByPage:" + hashKey;


//        查询本地缓存
        String localCachedValue = LOCAL_CACHE.getIfPresent(cacheKey);

        //缓存命中
        if (localCachedValue != null) {
            Page<PictureVO> cachedPage = JSONUtil.toBean(localCachedValue, Page.class);

            return ResultUtils.success(cachedPage);
        }

        //查询Redis
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String redisCacheValue = opsForValue.get(cacheKey);
        //查询命中
        if (redisCacheValue != null) {
            //将结果放入本地缓存
            LOCAL_CACHE.put(cacheKey, redisCacheValue);
            Page<PictureVO> cachedPage = JSONUtil.toBean(redisCacheValue, Page.class);

            return ResultUtils.success(cachedPage);
        }

        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));

        //获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);


        //将数据库中的结果放入缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        LOCAL_CACHE.put(cacheKey, cacheValue);
        long timeout = 300 + RandomUtil.randomLong(0, 300);//设置较为随机的过期时间,防止缓存雪崩
        opsForValue.set(cacheKey, cacheValue, timeout, TimeUnit.SECONDS);


        // 返回封装类
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 管理员审核图片
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> pictureReview(@RequestBody PictureReviewRequest pictureReviewRequest,
                                               HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 用户编辑图片
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.editPicture(pictureEditRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 以图搜图
     *
     * @param searchPictureByPictureRequest
     * @return
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> getPictureListByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> imageSearchResults = ImageSearchApiFacade.searchImages(oldPicture.getOriginalUrl() == null ? oldPicture.getUrl() : oldPicture.getOriginalUrl());
        return ResultUtils.success(imageSearchResults);

    }

    /**
     * 根据颜色搜索图片
     *
     * @param searchPictureByColorRequest
     * @param request
     * @return
     */
    @PostMapping("/search/color")
    public BaseResponse<List<PictureVO>> getPictureVOListByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        String picColor = searchPictureByColorRequest.getPicColor();
        List<PictureVO> pictureVOListByColor = pictureService.getPictureVOListByColor(spaceId, picColor, userService.getLoginUser(request));
        return ResultUtils.success(pictureVOListByColor);
    }

    @PostMapping("/edit/batch")
    public BaseResponse<Boolean> editPictureBatch(@RequestBody PictureEditByBatchRequest pictureEditBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureEditBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.pictureEditByBatch(pictureEditBatchRequest, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 创建Ai扩图任务
     */
    @PostMapping("/out_painting/create_task")
    public BaseResponse<CreateOutPaintingTaskResponse> createOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskRequest request,HttpServletRequest  servletRequest) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        CreateOutPaintingTaskResponse pictureOutPaintTask = pictureService.createPictureOutPaintTask(request, userService.getLoginUser(servletRequest));
        return ResultUtils.success(pictureOutPaintTask);
    }

    /**
     * 查询Ai扩图任务处理结果
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponseResult> getOutPaintingTaskResult(@RequestParam String taskId) {
        ThrowUtils.throwIf(taskId == null, new BusinessException(ErrorCode.PARAMS_ERROR, "任务id不能为空"));

        GetOutPaintingTaskResponseResult outPaintingTaskResult = aliyunAiService.getOutPaintingTaskResult(taskId);
        return ResultUtils.success(outPaintingTaskResult);
    }

    /**
     * 获取标签和分类列表
     *
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意", "萌宠", "美景");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报", "风景");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }


    @GetMapping("/setColor")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> setPictureListColor() {
        pictureService.setPictureListColor();
        return ResultUtils.success("设置成功");
    }


    /**
     * 将公共空间图片复制到用户空间
     * @param copyToSpaceRequest
     * @param request
     * @return
     */
    @PostMapping("/copyToSpace")
    public BaseResponse<PictureVO> copyToSpace(@RequestBody CopyToSpaceRequest copyToSpaceRequest,HttpServletRequest  request) {
        Long sourceId = copyToSpaceRequest.getSourceId();
        Long targetSpaceId = copyToSpaceRequest.getTargetSpaceId();


        Picture source = pictureService.getById(sourceId);

        User loginUser = userService.getLoginUser(request);

        // 复制图片元数据并关联新空间
        PictureVO newPicture = pictureService.copyPicture(source, targetSpaceId, loginUser);
        return ResultUtils.success(newPicture);
    }
}
